import React, {memo, useEffect, useState} from 'react';
import Header from "../../../components/main-header/Header";

import "./dataManager.css";
import Title from "../../../components/Title/Title";
import {useDispatch, useSelector} from "react-redux";
import {saveDataManagerInfo} from "./store/actionCreators";
import {message} from "antd";
import request from "../../../services/request";
import {BASE_URL} from "../../../services/config";
import {deepClone, getContextPath} from "../../../common/utils";

export default memo(function DataManager() {
  const dispatch = useDispatch();
  const {dataManagerInfo, data, isCN} = useSelector(state => ({
    dataManagerInfo: state.dataManagerReducer.dataManagerInfo,
    data: state.dataReducer.data,
    isCN: state.languageReducer.isCN
  }));
  const [protocol, setProtocol] = useState([]);
  const [experiment, setExperiment] = useState([]);
  const [DMObj, setDMObj] = useState({ip: data.connectPort});
  const [workspaceIndex, setWorkspaceIndex] = useState(-1);
  const [protocolIndex, setProtocolIndex] = useState(-1);
  const [experimentIndex, setExperimentIndex] = useState(-1);
  const [url, setUrl] = useState("");
  let cloneData = {};
  let cloneDMObj = {};
  const config = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/dataManager/uploadAZD`,
    headers: {
      authorization: 'authorization-text'
    },
    accept: ".AZD",
    onChange(info) {
      if (info.file.status === 'done') {
        if (!data.wells.some(it => it.targets.length !== 0)) {
          return message.warn("There is no Target in plate setting, please set Target first.");
        }
        setUrl("");
        const loadData = info.file.response.data;
        console.log(loadData);
        cloneData = deepClone(data, cloneData);
        cloneData.meltDataOrigin = loadData.meltData.data;
        cloneData.pcrDataOrigin = loadData.quantificationData;
        //  TODO: 把AZD的所有数据都要保存到data里,不能只保存有target的,这样会报错
        cloneData.wells.forEach(well => {
          if (well.targets.length === 0) {
            return;
          }
          const azdIndex = well.col * 8 + well.row; //  AZD中的数据是竖着算的,D3对应19,cqa中D3对应38
          well.meltData = loadData.meltData.data[azdIndex];
          well.targets.forEach(target => well.lines[target.channelIndex].quantificationOrigin = loadData.quantificationData[`channel${target.channelIndex + 1}`][azdIndex]);
        });
        request({
          url: 'analysis/calAll',
          data: cloneData,
          method: 'post'
        })
          .then(res => {
            switch (res.code) {
              case 200:
                request({
                  url: 'downloadAction/downloadAll',
                  data: {
                    experimentName: DMObj.experimentDataName,
                    userName: cloneData.userName,
                    data: JSON.stringify(res.data)
                  },
                  method: 'post'
                }).then(() => {
                  setUrl(getContextPath() + "/downloadAction/downloadAllUrl");
                }).catch(err => message.error(err));
                break;
              case 500:
                message.error(res.message);
                break;
              default:
                message.error("error");
                // TODO: 排查错误
                console.log(res);
            }
          })
          .catch(err => message.error(err));
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };
  useEffect(() => {
    if (!url) {
      return;
    }
    let iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.style.display = "none";
    document.body.appendChild(iframe);
    setTimeout(() => iframe.remove(), 1000);
  }, [url]);

  //  刷新
  function refresh() {
    request({
      url: "dataManager/refresh",
      data: data.connectPort,
      method: "post"
    }).then(res => {
      switch (res.code) {
        case 200:
          console.log(res.data);
          dispatch(saveDataManagerInfo(res.data));
          break;
        case 500:
          message.warn(res.message);
          break;
        default:
          message.error("Please try again.");
      }
    }).catch(err => message.error(err));
  }

  //  选择Workspace
  function selectWorkspace(name, indey) {
    cloneDMObj = deepClone(DMObj, cloneDMObj);
    cloneDMObj.workSpaceName = name;
    setDMObj(cloneDMObj);
    dataManagerInfo.find(it => it.name === name && setProtocol(it.protocols));
    setWorkspaceIndex(indey);
    setExperiment([]);
    setExperimentIndex(-1);
    setProtocolIndex(-1);
  }

  //  选择Protocol
  function selectProtocol(name, indey) {
    cloneDMObj = deepClone(DMObj, cloneDMObj);
    cloneDMObj.protocolName = name;
    setDMObj(cloneDMObj);
    protocol.find(it => it.name === name && setExperiment(it.experiments));
    setProtocolIndex(indey);
    setExperimentIndex(-1);
  }

  //  选择Experiment
  function selectExperiment(obj, indey) {
    cloneDMObj = deepClone(DMObj, cloneDMObj);
    cloneDMObj.experimentDataName = obj.name;
    cloneDMObj.experimentBeginDate = obj.beginDate;
    cloneDMObj.experimentEndDate = obj.endDate;
    setDMObj(cloneDMObj);
    setExperimentIndex(indey);
  }

  //  保存AZD文件
  function saveAZD() {
    if (!data.wells.some(it => it.targets.length !== 0)) {
      return message.warn("There is no Target in plate setting, please set Target first.");
    }
    setUrl("");
    request({
      url: "dataManager/download",
      data: DMObj,
      method: "post"
    }).then(res => {
      switch (res.code) {
        case 200:
          const loadData = res.data;
          cloneData = deepClone(data, cloneData);
          cloneData.meltDataOrigin = loadData.meltData.data;
          cloneData.pcrDataOrigin = loadData.quantificationData;
          cloneData.wells.forEach(well => {
            if (well.targets.length === 0) {
              return;
            }
            const azdIndex = well.col * 8 + well.row; //  AZD中的数据是竖着算的,D3对应19,cqa中D3对应38
            well.meltData = loadData.meltData.data;
            well.targets.forEach(target => well.lines[target.channelIndex].quantificationOrigin = loadData.quantificationData[`channel${target.channelIndex + 1}`][azdIndex]);
          });
          request({
            url: 'downloadAction/downloadAll',
            data: {
              experimentName: DMObj.experimentDataName,
              userName: cloneData.userName,
              data: JSON.stringify(cloneData)
            },
            method: 'post'
          }).then(() => {
            setUrl(getContextPath() + "/downloadAction/downloadAllUrl");
            message.info("Save AZD success");
          }).catch(err => message.error(err));
          break;
        case 500:
          message.warn(res.message);
      }
    }).catch(err => message.error(err));
  }

  return (
    <div>
      <Header name={isCN ? "数据管理" : "DataManager"} imgPosition="-300px"
              isSave={true}
              isLoad={true}
              isRefresh={true}
              isDataManagerLoad={true}
              refreshAction={refresh}
              loadConfig={config}
              saveAction={saveAZD}
      />
      <section className="mainSection dataManagerPage">
        <div>
          <Title name={isCN ? "工作面板名称" : "Workspace Name"}/>
          <ul className="scrollBarStyle">
            {
              dataManagerInfo.map((it, index) => (
                <li key={it.name}
                    style={index === workspaceIndex ? {backgroundColor: "#ccc"} : null}
                    onClick={() => selectWorkspace(it.name, index)}
                >{it.name}</li>
              ))
            }
          </ul>
        </div>
        <div>
          <Title name={isCN ? "程序名称" : "Protocol Name"}/>
          <ul className="scrollBarStyle">
            {
              protocol.map((it, index) => (
                <li key={it.name}
                    style={index === protocolIndex ? {backgroundColor: "#ccc"} : null}
                    onClick={() => selectProtocol(it.name, index)}
                >{it.name}</li>
              ))
            }
          </ul>
        </div>
        <div>
          <header>
            <div>{isCN ? "实验名称" : "Exp.Name"}</div>
            <div>{isCN ? "开始时间" : "Begin Data"}</div>
            <div>{isCN ? "结束时间" : "End Name"}</div>
          </header>
          <section className="scrollBarStyle">
            {
              experiment.map((it, index) => (
                <ul key={it.name}
                    style={index === experimentIndex ? {backgroundColor: "#ccc"} : null}
                    onClick={() => selectExperiment(it, index)}
                >
                  <li>{it.name}</li>
                  <li>{it.beginDate}</li>
                  <li>{it.endDate}</li>
                </ul>
              ))
            }
          </section>
        </div>
      </section>
    </div>
  );
});